package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询商铺类型
     * @return
     */
    public Result queryShopType() {
        // 1.从redis中查询所有的商铺分类
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(RedisConstants.SHOP_TYPE_LIST_KEY, 0, -1);
        // 2.不为空则直接返回
        if (shopTypeList != null && shopTypeList.size() > 0) {
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeList.get(0), ShopType.class);
            return Result.ok(shopTypes);
        }
        // 3.如果为空，则查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 4.数据库查询为空，则返回错误信息
        if (typeList == null || typeList.size() == 0) {
            return Result.fail("店铺查询失败！");
        }
        // 5.数据库查询不为空，则存入redis
        stringRedisTemplate.opsForList().leftPushAll(RedisConstants.SHOP_TYPE_LIST_KEY, JSONUtil.toJsonStr(typeList));
        // 6.返回
        return Result.ok(typeList);
    }
}
